package cn.weixin.service.token;

import static cn.weixin.common.config.AppConfig.APPID;
import static cn.weixin.common.config.AppConfig.SECRET;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import cn.weixin.common.util.HttpUtil;
import cn.weixin.config.UrlConfig;

import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * @author Han
 */
public class TokenUtil {
	private static final String GRANT_TYPE = "client_credential";
	
	protected static String getToken(){
		
		Map<String,String> map = new HashMap<String,String>();
		map.put("grant_type", GRANT_TYPE);
		map.put("appid", APPID);
		map.put("secret", SECRET);
		
		String response = HttpUtil.executeGet(UrlConfig.TOKEN_URL, map);
		
		ObjectMapper mapper = new ObjectMapper();
		
		try {
			Map<String,String> result = mapper.readValue(response, Map.class);
			if(result != null){
				String token = result.get("access_token");
				if(StringUtils.isNotBlank(token)){
					return token;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
